<?php
namespace app\admin\controller;

use app\common\controller\Base;
use app\common\service\UserRole as UserRoleService;
use app\common\service\UserPermission as UserPermissionService;
use think\Request;

class Role extends Base{

    public function index(){

        $userRoleService = new UserRoleService();
        $roles = $userRoleService ->getRoles();

        return view('',['roles'=>$roles]);

    }

    public function add(){

        $userPermissionService = new UserPermissionService();
        $permissions = $userPermissionService -> getAllPermissions();

        return view('',['permissions'=>$permissions]);
    }


    public function create(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request -> only(['name','permission']);
        $data['permission'] = array_keys($data['permission']);
        $data['permission'] = serialize($data['permission']);

        $userRoleService = new UserRoleService();
        $result = $userRoleService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }
    }


    public function edit(Request $request){
        $id = $request->only("id")['id'];

        $userRoleService = new UserRoleService();
        $role = $userRoleService->getRole(intval($id));

        $userPermissionService = new UserPermissionService();
        $permissions = $userPermissionService -> getAllPermissions();

        return view('',['role'=>$role,'permissions'=>$permissions]);
    }

    public function update(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request -> only(['id','name','permission']);
        $data['permission'] = array_keys($data['permission']);
        $data['permission'] = serialize($data['permission']);

        $userRoleService = new UserRoleService();
        $result = $userRoleService ->update($data);

        if(1 == $result['state']) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }


    public function delete(Request $request){

        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }

        $id = $request->only(['id']);
        if(count($id) !== 1){
            $this->error("禁止批量操作");
        }
        $userRoleService = new UserRoleService();

        $count = $userRoleService -> delete($id);

        if($count){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }

    }
}